#!/usr/bin/env bash

# shellcheck disable=SC2034
services=("portal" "trade" "user")
mqs=("portal" "trade")
apis=("portal" "trade" "user")

export HIGHWAY_DEBUG=true

build_service() {
  process_name="$1"
  process_path="$2"
  if [ ! -d "${process_path}/log" ]; then
      echo "mkdir log"
      mkdir -p "${process_path}/log"
  else
      echo "log exists"
  fi
  echo "building ${process_name}"
  cd "${process_path}" && go build -o "build/${process_name}"
  echo "${process_name} built"
  cd ../../../
}

start_service() {
  process_name="$1"
  process_path="$2"
  process_pid=$(pgrep "${process_name}")
  echo "starting ${process_name}"
  if [[ -z ${process_pid} ]]; then
      cd "${process_path}" && nohup "./build/${process_name}" > "log/info.log" &
      echo "${process_name} started"
      sleep 1
      process_pid=$(pgrep "${process_name}")
      echo "${process_name} started pid: ${process_pid}"
  else
    echo "${process_name} already started pid: ${process_pid}"
  fi
}

stop_service() {
  process_name="$1"

  echo "stopping ${process_name}"
  # pid
  process_pid=$(pgrep "${process_name}")
  if [ -z "$process_pid" ]; then
      echo "${process_name} already stopped"
  else
    kill "$process_pid"
    echo "${process_name} stopped pid: ${process_pid}"
  fi
}